/******************************************************************************
 * @File name   :      MemberPackageServiceImpl.java
 *
 * @Author      :      JIZHANGS
 *
 * @Date        :      Jul 28, 2015
 *
 * @Copyright Notice: 
 * Copyright (c) 2015 Capgemini, Inc. All  Rights Reserved.
 * This software is published under the terms of the Capgemini Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * Jul 28, 2015 9:33:15 AM        JIZHANGS     1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.crmdp.dealer.purchase.service.impl;

import java.io.File;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.cap.bts.commonfunc.common.constant.SmsTemplateNoConstants;
import com.cap.bts.commonfunc.common.constant.SmsTemplateVariable;
import com.cap.bts.commonfunc.common.dto.SmsContentDetailDto;
import com.cap.bts.crmdp.commons.sftp.SFTPProcessor;
import com.cap.bts.crmdp.commons.sftp.SftpProperties;
import com.cap.bts.crmdp.dealer.card.service.ICardExportService;
import com.cap.bts.crmdp.dealer.mars.constants.MARSConstants;
import com.cap.bts.crmdp.dealer.masterdata.dao.IMaintainDealerDao;
import com.cap.bts.crmdp.dealer.masterdata.domain.MasterDataDealerInfo;
import com.cap.bts.crmdp.dealer.member.dao.IMaintainCarPlateDao;
import com.cap.bts.crmdp.dealer.member.dao.IMaintainMemberDao;
import com.cap.bts.crmdp.dealer.member.domain.CarPlateInfo;
import com.cap.bts.crmdp.dealer.member.domain.MemberInfo;
import com.cap.bts.crmdp.dealer.purchase.constants.PurchaseConstants;
import com.cap.bts.crmdp.dealer.purchase.dao.ICardInventoryDao;
import com.cap.bts.crmdp.dealer.purchase.dao.IMemberPackageDao;
import com.cap.bts.crmdp.dealer.purchase.dao.IPackageDefinitionDao;
import com.cap.bts.crmdp.dealer.purchase.domain.CardInventory;
import com.cap.bts.crmdp.dealer.purchase.domain.MemberPackageInfo;
import com.cap.bts.crmdp.dealer.purchase.domain.PackageDefinition;
import com.cap.bts.crmdp.dealer.purchase.dto.MemberPackageInfoSubmitDto;
import com.cap.bts.crmdp.dealer.purchase.dto.PackageExpireDto;
import com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService;
import com.cap.bts.crmdp.dealer.redemption.dao.IPackageRedemptionDao;
import com.cap.bts.crmdp.dealer.redemption.dto.MemberAndDealerInfoDto;
import com.cap.bts.crmdp.dealer.redemption.dto.MemberPackagesReportDto;
import com.cap.bts.crmdp.dealer.redemption.dto.ShowMemberPackageInfoReportDto;
import com.cap.bts.crmdp.webservice.dto.WSCrmCancelOrderResultDto;
import com.cap.bts.crmdp.webservice.dto.WSCrmOrderDto;
import com.cap.bts.crmdp.webservice.dto.WSCrmSettlementDto;
import com.cap.bts.crmdp.webservice.dto.WSCrmSettlementResultDto;
import com.cap.bts.framework.codemapping.domain.CodeInfo;
import com.cap.bts.framework.codemapping.service.ICodeMapping;
import com.cap.bts.framework.common.constant.CodeMappingType;
import com.cap.bts.framework.common.constant.CommonConstants;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.service.impl.BaseServiceImpl;
import com.cap.bts.framework.common.util.Utils;
import com.cap.bts.framework.sms.service.ISmContentService;
import com.cap.bts.framework.usermgnt.dao.IUserDao;
import com.cap.bts.framework.usermgnt.domain.User;
import com.jcraft.jsch.ChannelSftp;

/**
 *
 */
@Transactional(rollbackFor = AppException.class)
@Service
public class MemberPackageServiceImpl extends BaseServiceImpl implements IMemberPackageService {

    private static final Logger LOGGER = Logger.getLogger(MemberPackageServiceImpl.class);

    @Resource(name = "memberPackageDao")
    private IMemberPackageDao memberPackageDao;

    @Autowired
    private IMaintainMemberDao memberDao;

    @Autowired
    private IMaintainCarPlateDao carPlateDao;
    
    
    @Autowired
    private IPackageDefinitionDao packageDefinitionDao;
    
    @Autowired
    private ICardInventoryDao cardInventoryDao;

    
    @Autowired
    private ISmContentService smContentService;

    @Autowired
    private ICodeMapping codeMappingService;

    @Autowired
    private IUserDao userDao;
    
    @Autowired
    private IMaintainDealerDao dealerDao;
    @Autowired
    private IPackageRedemptionDao packageRedemptionDao;
    @Autowired
    private ICardExportService cardExportService;

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Jul 28, 2015
     * @see com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService#checkMemberPackageExsit(com.cap.bts.crmdp.dealer.purchase.dto.MemberPackageInfoSubmitDto)
     **/
    @Override
    public Boolean checkMemberPackageExsit(MemberPackageInfoSubmitDto dto) throws AppException {
        MemberPackageInfo mpi = new MemberPackageInfo();
        PackageDefinition pd = new PackageDefinition();
        pd.setId(dto.getPackageDefId());
    	mpi.setPackageDefinition(pd);
    	mpi.setPackageNumber(dto.getPackageNumber());
    	mpi = memberPackageDao.getUnPurchaseMemberPackageInfo(mpi);
    	if (mpi == null) {
    		return false;
    	}
    	return true;
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Aug 4, 2015
     * @see com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService#updateMemberPackageInfo(com.cap.bts.crmdp.dealer.purchase.domain.MemberPackageInfo)
     **/
    @Override
    public void updateMemberPackageInfo(MemberPackageInfo mpi) throws AppException {
        memberPackageDao.updateMemberPackageInfo(mpi);
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Aug 4, 2015
     * @see com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService#updateMemberPackageInfo(com.cap.bts.crmdp.dealer.purchase.domain.MemberPackageInfo)
     **/
    @Override
    public void updateMemberPackageInfoById(MemberPackageInfo mpi) throws AppException {
        memberPackageDao.updateMemberPackageInfoById(mpi);
    }

    private int getDays(Date startDate, Date endDate) {
        Date tempDate = endDate;
        if (tempDate == null) {
            tempDate = new Date();
        }
        Long start = startDate.getTime();
        Long end = tempDate.getTime();
        Long quot = start - end;
        return (int) (quot / (1000 * 60 * 60 * 24));
    }

    private void sendExpiredSMS(MemberPackageInfo memberPackageInfo, String templateNo)
        throws AppException {
        try {
            MemberInfo memberInfo = memberDao.findById(memberPackageInfo.getActiveMemberId());
            CarPlateInfo carPlateInfo = carPlateDao.findById(memberPackageInfo.getActiveCarId());
            User user = userDao.getUserByDealerId(memberPackageInfo.getActiveDealerId());
            if (memberInfo != null && carPlateInfo != null && user != null) {
                // Send SMS
                Map<String, String> paraMap = new HashMap<String, String>();
                paraMap.put(SmsTemplateVariable.VARIABLE_MEMBER_NAME, memberInfo.getMemberName());
                paraMap.put(SmsTemplateVariable.VARIABLE_CAR_PLATE_NUMBER,
                    carPlateInfo.getCarPlate());
                paraMap.put(SmsTemplateVariable.VARIABLE_PACKAGE_NAME, memberPackageInfo
                    .getPackageDefinition().getName());
                paraMap.put(SmsTemplateVariable.VARIABLE_PACKAGE_NUM,
                    memberPackageInfo.getPackageNumber());
                paraMap.put(SmsTemplateVariable.VARIABLE_DEALER_NAME, user.getName());

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                paraMap.put(SmsTemplateVariable.VARIABLE_EXPIRE_DATE,
                    sdf.format(memberPackageInfo.getExpireDate()));
                paraMap.put(SmsTemplateVariable.VARIABLE_PURCHASE_DATE,
                    sdf.format(memberPackageInfo.getPurchaseDate()));
                SmsContentDetailDto smsDto = new SmsContentDetailDto();
                smsDto.setParaMap(paraMap);
                if (Utils.notEmpty(memberInfo.getMobilePhone())) {
                    smsDto.setDestMobile(Long.valueOf(memberInfo.getMobilePhone()));
                    smsDto.setTemplateNo(templateNo);
                    smContentService.createSmsContent(smsDto);

                }
            }
        } catch (Exception e) {
            throw new AppException("Exception sendExpiredSMS", e);
        }
    }
    
    private void sendExpiredSMS(PackageExpireDto memberPackageInfo, String templateNo)
            throws AppException {
            try {
                MasterDataDealerInfo dealer = dealerDao.getDealerByDealerNum(String.valueOf(memberPackageInfo.getActiveDealerId()));
                if (memberPackageInfo != null && dealer != null) {
                    // Send SMS
                    Map<String, String> paraMap = new HashMap<String, String>();
                    paraMap.put(SmsTemplateVariable.VARIABLE_MEMBER_NAME, memberPackageInfo.getMemberName());
                    paraMap.put(SmsTemplateVariable.VARIABLE_CAR_PLATE_NUMBER,
                    		memberPackageInfo.getCarPlate());
                    paraMap.put(SmsTemplateVariable.VARIABLE_PACKAGE_NAME, memberPackageInfo.getName());
                    paraMap.put(SmsTemplateVariable.VARIABLE_PACKAGE_NUM,
                        memberPackageInfo.getPackageNumber());
                    paraMap.put(SmsTemplateVariable.VARIABLE_DEALER_NAME, dealer.getDealerName());

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    paraMap.put(SmsTemplateVariable.VARIABLE_EXPIRE_DATE,
                        sdf.format(memberPackageInfo.getExpireDate()));
                    paraMap.put(SmsTemplateVariable.VARIABLE_PURCHASE_DATE,
                        sdf.format(memberPackageInfo.getPurchaseDate()));
                    SmsContentDetailDto smsDto = new SmsContentDetailDto();
                    smsDto.setParaMap(paraMap);
                    if (Utils.notEmpty(memberPackageInfo.getMobilePhone())) {
                        smsDto.setDestMobile(Long.valueOf(memberPackageInfo.getMobilePhone()));
                        smsDto.setTemplateNo(templateNo);
                        smContentService.createSmsContent(smsDto);

                    }
                }
            } catch (Exception e) {
                throw new AppException("Exception sendExpiredSMS", e);
            }
        }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : 2015年9月5日
     * @see com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService#getMemberPackageInfoByActiveDealerIdAndActiveMemberId(java.lang.Long,
     *      java.lang.Long)
     **/
    @Override
    public List<MemberPackageInfo> getMemberPackageInfoByActiveDealerIdAndActiveMemberId(
        Long dealerId, Long memberId) throws AppException {
        return memberPackageDao.getMemberPackageInfoByActiveDealerIdAndActiveMemberId(dealerId,
            memberId);
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : 2015年9月6日
     * @see com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService#updateMemberPackageInfoByMemberPackageInfo(com.cap.bts.crmdp.dealer.purchase.domain.MemberPackageInfo)
     **/
    @Override
    public void updateMemberPackageInfoByMemberPackageInfo(MemberPackageInfo memberPackageInfo,
        Long newMemberId) throws AppException {
        memberPackageDao.updateMemberPackageInfoByMemberPackageInfo(memberPackageInfo, newMemberId);
    }

    @Override
    public void processNotificationBeforeActivication() throws AppException {

        try {
            List<MemberPackageInfo> memberPackageInfoList = memberPackageDao
                .getMemberPackageList(PurchaseConstants.PACKAGE_STATUS_SALED);
            for (MemberPackageInfo memberPackageInfo : memberPackageInfoList) {
                if (memberPackageInfo != null) {
                    Calendar currentCalendar = Calendar.getInstance();
                    currentCalendar.setTime(new Date());
                    Calendar purchaseCalendar = Calendar.getInstance();
                    purchaseCalendar.setTime(memberPackageInfo.getPurchaseDate());
                    // add one month
                    purchaseCalendar.add(Calendar.MONTH, 1);

                    if (currentCalendar.after(purchaseCalendar)) {
                        memberPackageInfo
                            .setStatus((byte) PurchaseConstants.PACKAGE_STATUS_EXPIRED);
                        memberPackageDao.update(memberPackageInfo);
                        sendExpiredSMS(memberPackageInfo,
                            SmsTemplateNoConstants.PACKAGE_EXPIRED_TEMPLATE_NO);
                    }

                }
            }
        } catch (Exception e) {
            throw new AppException("Exception processExpiredMemberPackage", e);
        }

    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Oct 16, 2015
     * @see com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService#getMaxMemberPackageInfoByCardPrefix(java.lang.String)
     **/
    @Override
    public MemberPackageInfo getMaxMemberPackageInfoByNonPhysicalCardPrefix(String perfix) throws AppException {
        return memberPackageDao.getMaxMemberPackageInfoByNonPhysicalCardPrefix(perfix);
    }
    
    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Oct 16, 2015
     * @see com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService#getMaxMemberPackageInfoByCardPrefix(java.lang.String)
     **/
    @Override
    public MemberPackageInfo getMaxMemberPackageInfoByPhysicalCardPrefix(String perfix) throws AppException {
        return memberPackageDao.getMaxMemberPackageInfoByPhysicalCardPrefix(perfix);
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Oct 21, 2015
     * @see com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService#cancelOrder(com.cap.bts.crmdp.dealer.purchase.domain.MemberPackageInfo)
     **/
    @Override
    public WSCrmCancelOrderResultDto cancelOrder(WSCrmOrderDto dto) {
        WSCrmCancelOrderResultDto resultDto = new WSCrmCancelOrderResultDto();
        MemberPackageInfo updateDto = null;
        MemberPackageInfo mpi = new MemberPackageInfo();
        try {
            if (dto.getCardNumberList() != null) {
                for (String cardNumber : dto.getCardNumberList()) {
                    mpi.setPackageNumber(cardNumber);
                    MemberPackageInfo memberPackageInfo = memberPackageDao
                        .getCancelMemberPackageInfoMars(mpi);
                    if (memberPackageInfo != null) {
                        updateDto = memberPackageDao.findById(memberPackageInfo.getId());
                    }
                    if (updateDto != null) {
                        PackageDefinition packageDefinition=packageDefinitionDao.getPackageDefinitionInfoById(updateDto.getPackageDefinition().getId());
                        //增加库存
                        if(packageDefinition!=null){
                            CardInventory ci=cardInventoryDao.getCardInventoryInfo(packageDefinition.getCardDefinition().getId(), updateDto.getDealerId());
                            ci.setOnhandQuantity(ci.getOnhandQuantity()+1);
                        }
                        
                        if (updateDto.getCardDefinition().getIsPhysicalCard() == 1) {
                            updateDto.setCarId(null);
                            updateDto.setDealerId(null);
                            updateDto.setMemberId(null);
                            updateDto.setPurchaseDate(null);
                            updateDto.setActualPrice(null);
                            updateDto.setPackageNumber(cardNumber);
                            updateDto.setStatus((byte) 0);
                            updateDto.setPackageDefinition(null);
                            updateDto.setMarsLockStatus(0);
                            updateDto.setSoNumberCancel(dto.getSoNumber());
                            memberPackageDao.update(updateDto);
                        } else {
                            memberPackageDao.remove(updateDto.getId());
                        }
                    }
                }
            }else{
                resultDto.setStatusCode(MARSConstants.RESULT_STATUS_CODE_FAIL);
                resultDto.setResultMessage("cardNumberList is null");
                return resultDto;
            }
        } catch (Exception e) {
            resultDto.setStatusCode(MARSConstants.RESULT_STATUS_CODE_FAIL);
            resultDto.setResultMessage(e.getLocalizedMessage());
            LOGGER.error("cancelOrder", e);
            return resultDto;
        }
        resultDto.setStatusCode(MARSConstants.RESULT_STATUS_CODE_SUCCESS);
        resultDto.setResultMessage("success");
        return resultDto;
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Oct 23, 2015
     * @see com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService#settlement(com.cap.bts.crmdp.webservice.dto.WSCrmOrderDto)
     **/
    @Override
    public WSCrmSettlementResultDto settlement(WSCrmSettlementDto dto) {
        WSCrmSettlementResultDto resultDto = new WSCrmSettlementResultDto();
        MemberPackageInfo updateDto = null;
        MemberPackageInfo mpi = new MemberPackageInfo();
        try {
            if (dto.getCardNumberList() != null) {
                for (String cardNumber : dto.getCardNumberList()) {
                    mpi.setPackageNumber(cardNumber);
                    MemberPackageInfo memberPackageInfo = memberPackageDao
                        .getCancelMemberPackageInfoMars(mpi);
                    if (memberPackageInfo != null) {
                        updateDto = memberPackageDao.findById(memberPackageInfo.getId());
                    }
                    if (updateDto != null) {
                        if (updateDto.getCardDefinition().getIsPhysicalCard() == 1) {
                            resultDto.setActivation("1");
                        } else {
                            resultDto.setActivation("0");
                        }
                        resultDto.setStatusCode("1");
                        resultDto.setResultMessage("success");
                        
                        updateDto.setMarsLockStatus(0);
                        updateDto.setSoNumberSettle(dto.getSoNumber());
                        
                        memberPackageDao.update(updateDto);
                    }
                }
            }else{
                resultDto.setStatusCode(MARSConstants.RESULT_STATUS_CODE_FAIL);
                resultDto.setResultMessage("cardNumberList is null");
                return resultDto;
            }
        } catch (Exception e) {
            resultDto.setStatusCode("0");
            resultDto.setResultMessage(e.getLocalizedMessage());
            LOGGER.error("settlement", e);
            return resultDto;
        }
        return resultDto;
    }
    
    
    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Oct 29, 2015
     * @see com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService#getPackageListForReportByMember(java.lang.Long, java.lang.Long)
     **/
    @Override
    public List<MemberPackagesReportDto> getPackageListForReportByMember(Long memberId, Long carId) throws AppException {
    	List<MemberPackagesReportDto> dataList = new ArrayList<MemberPackagesReportDto>();
    	
    	Map<Long, MemberPackagesReportDto> plateMap = new HashMap<Long, MemberPackagesReportDto>();
    	
    	MemberPackagesReportDto nonePlate = new MemberPackagesReportDto();
    	if(carId == null){
    		//不显示未激活卡
    		dataList.add(nonePlate);
    	}
    	
    	//获取套餐信息
    	List<Object[]> list = memberPackageDao.getPackageListForReportByMember(memberId, carId);
    	
    	List<ShowMemberPackageInfoReportDto> packageList = new ArrayList<ShowMemberPackageInfoReportDto>(); 
    	
    	List<Long> packageIdList = new ArrayList<Long>();
    	Map<Long, ShowMemberPackageInfoReportDto> map = new HashMap<Long, ShowMemberPackageInfoReportDto>();
    	
    	for(Object[] obj : list){
    		ShowMemberPackageInfoReportDto packageDto = new ShowMemberPackageInfoReportDto();
    		
    		packageDto.setPrice((Double) obj[0]);
    		packageDto.setName((String)obj[1]);
    		packageDto.setPackageNumber((String)obj[2]);
    		packageDto.setStatus((Byte)obj[3]);
    		packageDto.setPurchaseDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,(Date)obj[4]));
    		packageDto.setActiveDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,(Date)obj[5]));
    		packageDto.setExpireDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,(Date)obj[6]));
    		BigInteger id = (BigInteger) obj[7];
    		packageDto.setId(id.longValue());
    		BigInteger tmpCarId = (BigInteger)obj[8];
    		if(tmpCarId != null){
    			packageDto.setCarId(tmpCarId.longValue());
    		}
    		packageDto.setCarPlate((String)obj[9]);
    		if(packageDto.getStatus() == 3){
    			packageDto.setHasUnActived(true);
    		}else{
    			packageDto.setHasUnActived(false);
    		}
    		String benfit = (String)obj[10];
    		if(benfit != null){
    		    packageDto.setBenfit(benfit);
    		}
    		
    		map.put(packageDto.getId(), packageDto);
    		packageIdList.add(packageDto.getId());
    		packageList.add(packageDto);
    		
    		
    		if(null == packageDto.getCarId()){
    			nonePlate.getShowMemberPackageInfoReportList().add(packageDto);
    		}else{
    			MemberPackagesReportDto tmpPlate = plateMap.get(packageDto.getCarId());
    			if(tmpPlate == null){
    				tmpPlate = new MemberPackagesReportDto();
    				tmpPlate.setCarPlate(packageDto.getCarPlate());
    				dataList.add(tmpPlate);
    				plateMap.put(packageDto.getCarId(), tmpPlate);
    			}
    			
    			tmpPlate.getShowMemberPackageInfoReportList().add(packageDto);
    		}
    		
    		
    		if(packageDto.getStatus() > 1){
    			//套餐使用明细
    			List<Object[]> packageRedemList = packageRedemptionDao.getPackageRedemListByPackageId(packageDto.getId());
    			if(packageRedemList != null && !packageRedemList.isEmpty()){
    				packageDto.setPackageRedemList(packageRedemList);
    			}
    		}
    		
    	}
    	
    	
    	if(!packageIdList.isEmpty()){
    		//获取所有套餐明细信息
    		List<Object[]> detailList = packageRedemptionDao.getPackageListReportDetailByPackageIds(packageIdList);
    		
    		//将套餐明细归置套餐下
    		for (Object[] objects : detailList) {
    			
    			ShowMemberPackageInfoReportDto dto = map.get(((BigInteger)objects[0]).longValue());
    			if(dto != null){
    				dto.getMemberPackageList().add(objects);
    			}
    		}
    	}
    	
    	if(nonePlate.getShowMemberPackageInfoReportList().isEmpty()){
    		dataList.remove(nonePlate);
    	}
    	
    	
    	return dataList;
    	
    	
    }

	@Override
	public List<MemberAndDealerInfoDto> getMemberAndDealerInfoDtoByMARSIdAndDearId(Long dealerId, String marsMemberId)
			throws AppException {
		return memberPackageDao.getMemberAndDealerInfoDtoByMARSIdAndDearId(dealerId, marsMemberId);
	}

	@Override
	public List<String> getfileDataList() throws AppException {
		return memberPackageDao.getfileDataList();
	}

	@Override
	public List<Object[]> getExpireCompanyInfoFromDealerRelMars() throws AppException {
		return memberPackageDao.getExpireCompanyInfoFromDealerRelMars();
	}

	@Override
	public void processFileForExpirePackage(Object[] companyAndTenantId) throws AppException {
		try {
			StringBuilder fileName = new StringBuilder();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
			fileName.append(companyAndTenantId[1].toString()).append("_").append(dateFormat.format(new Date())).append(".csv");
			List<String> fileDataList = getExpirePackagefileDataList(companyAndTenantId[0].toString());
			String courseFile = getClass().getResource("/").getPath();
			String filePath = courseFile.replace("\\", "/");
			File finalFile = cardExportService.processCSVfile(fileName, filePath, fileDataList);
			String sftpInfo = codeMappingService.getCodeValueByCode(PurchaseConstants.SFTP_INFO, PurchaseConstants.PACKAGEEXPIRATION);
			if(sftpInfo != null || sftpInfo != ""){
				SftpProperties sftpProperties = JSON.parseObject(sftpInfo, SftpProperties.class);
				SFTPProcessor ftpUtil = new SFTPProcessor();
				ChannelSftp channelSftp = ftpUtil.getConnect(sftpProperties);
				if(channelSftp.isConnected()){
					ftpUtil.uploadFile(finalFile.getAbsolutePath(), fileName.toString(), sftpProperties.getPath());
				}
				ftpUtil.closeChannel();
			}
		} catch (RuntimeException e) {
			throw new AppException("processFileForExpirePackage", e);
		} catch (Exception e) {
			throw new AppException("processFileForExpirePackage", e);
		}
	}

	@Override
	public List<String> getExpirePackagefileDataList(String company) throws AppException {
		return memberPackageDao.getExpirePackagefileDataList(company);
	}

	@Override
	public void processExpiredMemberPackageNew() throws AppException {
		List<Object[]> expireList = memberPackageDao.getActiveExpireMemberPackageList();
		if(expireList != null && !expireList.isEmpty()){
			List<CodeInfo> packageToBeExpiredDays = codeMappingService
					.getCodeInfoByType(CodeMappingType.PACKAGE_TO_BE_EXPIRED_DAYS
							.getValue());
			List<PackageExpireDto> list = new ArrayList<PackageExpireDto>();
			for (int i = 0; i < expireList.size(); i++) {
				PackageExpireDto dto = new PackageExpireDto(expireList.get(i));
				list.add(dto);
			}
            
			List<Long> idList = new ArrayList<Long>();
			final List<PackageExpireDto> expiredSmsList = new ArrayList<PackageExpireDto>();
			final List<PackageExpireDto> beforeSmsList = new ArrayList<PackageExpireDto>();
			
			Calendar currentCalendar = Calendar.getInstance();
			currentCalendar.add(Calendar.DAY_OF_MONTH, -1);
			
            for (PackageExpireDto memberPackageInfo : list) {
                if (memberPackageInfo != null
                    && Integer.valueOf(memberPackageInfo.getStatus()).intValue() == PurchaseConstants.PACKAGE_STATUS_ACTIVED) {
                    
                    Calendar expireCalendar = Calendar.getInstance();
                    expireCalendar.setTime(memberPackageInfo.getExpireDate());

                    if (currentCalendar.after(expireCalendar)){
                    	idList.add(memberPackageInfo.getPackageInfoId());
                    	//需要发送过期提醒短信
                    	expiredSmsList.add(memberPackageInfo);
                    } else {
                    	if("1".equals(codeMappingService.getCodeValueByCode("packageExpirationSMSIsOpen", "packageExpirationSMSIsOpen"))){
                    		if (packageToBeExpiredDays != null && !packageToBeExpiredDays.isEmpty()) {
                    			for (CodeInfo packageToBeExpiredDay : packageToBeExpiredDays) {
                    				int daysBeforeExpired = this.getDays(
                    						memberPackageInfo.getExpireDate(), new Date());
                    				if (daysBeforeExpired == Integer.valueOf(packageToBeExpiredDay
                    						.getValue())) {
                    					//需要发送过期前定期提醒短信
                    					beforeSmsList.add(memberPackageInfo);
                    				}
                    			}
                    		}
                    	}
                    }

                }
			}
	        //改状态
	        if(!idList.isEmpty()){
	        	String id = "";
	        	for (int i = 0; i < idList.size(); i++) {
	        		
	        		if(i > 0){
	        			id  += ",";
	        		}
	        		
					id +=  idList.get(i);
					
				}
	        	memberPackageDao.updatePackageStatusById(id, PurchaseConstants.PACKAGE_STATUS_EXPIRED);
	        }
	        //发送过期前定期提醒短信
	        if(beforeSmsList != null && !beforeSmsList.isEmpty()){
		        new Thread(){
					public void run(){
							for (int i = 0; i < beforeSmsList.size(); i++) {
								try {
									sendExpiredSMS(beforeSmsList.get(i),
									        SmsTemplateNoConstants.PACKAGE_TO_BE_EXPIRED_TEMPLATE_NO);
								} catch (AppException e) {
									LOGGER.error("SmsTemplateSend" , e);
								}
							}
						}
				}.start();
	        }
			 //发送过期提醒短信
			if(expiredSmsList != null && !expiredSmsList.isEmpty()){
		        new Thread(){
					public void run(){
							for (int i = 0; i < expiredSmsList.size(); i++) {
								try {
									sendExpiredSMS(expiredSmsList.get(i),
									        SmsTemplateNoConstants.PACKAGE_EXPIRED_TEMPLATE_NO);
								} catch (AppException e) {
									LOGGER.error("SmsTemplateSend" , e);
								}
							}
						}
				}.start();
			}
		}
		
		try {
			//生成文件传给SFTP
			//   tm_dealer_rel_mars company相关信息  dealer_rel_mars
			StringBuilder fileName = new StringBuilder();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
			fileName.append(PurchaseConstants.CRMEXPIRE).append("_").append(dateFormat.format(new Date())).append(".csv");
			List<String> fileDataList = getfileDataList();
			String courseFile = getClass().getResource("/").getPath();
			String filePath = courseFile.replace("\\", "/");
			File finalFile = cardExportService.processCSVfile(fileName, filePath, fileDataList);
			String sftpInfo = codeMappingService.getCodeValueByCode(PurchaseConstants.SFTP_INFO, PurchaseConstants.PACKAGEEXPIRATION);
			if(sftpInfo != null || sftpInfo != ""){
				SftpProperties sftpProperties = JSON.parseObject(sftpInfo, SftpProperties.class);
				SFTPProcessor ftpUtil = new SFTPProcessor();
				ChannelSftp channelSftp = ftpUtil.getConnect(sftpProperties);
				if(channelSftp.isConnected()){
					ftpUtil.uploadFile(finalFile.getAbsolutePath(), fileName.toString(), sftpProperties.getPath());
				}
				ftpUtil.closeChannel();
			}
			if(fileDataList != null && !fileDataList.isEmpty()){
				//生成每个company下的过期套餐信息文件并传给SFTP company有数据则生成，没有则不生成
				List<Object[]> conpanyList = getExpireCompanyInfoFromDealerRelMars();
				if(conpanyList != null && !conpanyList.isEmpty()){
					for(int i=0; i<conpanyList.size(); i++){
						processFileForExpirePackage(conpanyList.get(i));
					}
				}
			}
		} catch (Exception e) {
			throw new AppException("Exception processExpiredMemberPackage", e);
		}
	}
	


}
	
